<template>
  <div class="page-classifyList">
    <filter-view @update-list="() => getFilmMakerList()" />
    <a-table
      id="classifyTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false, onChange: onSelectChange }"
      :expandRowByClick="false"
      row-key="person_id"
      :columns="columns"
      :pagination="false"
      :data-source="state.filmMakerList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'person_avatar'">
          <a-image
            width="37.6px"
            height="39.85px"
            class="w-[-webkit-fill-available] object-contain"
            :src="getIcon(record)"
            :fallback="defaultImage"
          />
        </template>
        <template v-else-if="column.key === 'person_name'">
          <a-tooltip placement="top" color="#fff" v-if="record.person_name">
            <template #title>
              {{ record.person_name }}
            </template>
            <div class="ellipsis-text">{{ record.person_name }}</div>
          </a-tooltip>
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'person_gender'">
          <span>
            {{ getGender(record) }}
          </span>
        </template>
        <template v-if="column.key === 'person_categ_name'">
          <span>
            {{ record.person_categ_name || '-' }}
          </span>
        </template>
        <template v-if="column.key === 'person_area_name'">
          <span>
            {{ record.person_area_name || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'person_video_count'">
          <span>
            {{ formatNumber(record.person_video_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'person_popularity'">
          <span>
            {{ formatNumber(record.person_popularity) }}
          </span>
        </template>
        <template v-else-if="column.key === 'created_at'">
          <span>
            {{ formatToDateTime(+record.created_at * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'person_status'">
          <span>
            <a-switch
              v-model:checked="record.person_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="updateMaker(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteMaker(record)"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <a-pagination
      @change="handlePaginationChange"
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
    />
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该影人吗</span>
    </modal-view>
    <!-- 导入对话框 -->
    <modal-view
      title="提示"
      v-model:visible="importVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="importConfirm"
      @cancel="importCancel"
    >
      <span>确定要导入系统内置的影人库吗？</span>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed, inject } from 'vue'
import { message } from 'ant-design-vue'
import { formatNumber, formatToDateTime } from '@/utils/format'
import FilterView from './components/FilterView.vue'
import { column, makerData } from './dataSource'
import type { MakerListData } from '@/types/site/filmMakerList'
import ModalView from '@/components/components/modal/ModalView.vue'
import { makerState, statusState } from './state'
import router from '@/router'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import defaultImage from '@/assets/icon/defaultImage.png'
const {
  site: { maker_list, edit_status, maker_del }
} = apis
const columns = ref(column)
const deleteId = ref()
const deleteVisible = ref(false)
const importVisible = ref(false)
const imageDomain = inject('imageDomain') as any
console.log('imageDomain: ', imageDomain)
const baseUrl = computed(() => imageDomain?.person_cover || window.location.origin + '/')
const state = reactive<{ loading: boolean; filmMakerList: MakerListData[] }>({
  loading: false,
  filmMakerList: [] as MakerListData[]
})
const siteId = storage.get('siteId')
type Key = string
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getFilmMakerList()
}
//获取影人列表接口
const getFilmMakerList = () => {
  state.loading = true
  // 更新列表接口
  const params = {
    ...makerState,
    ...queryState
  }
  if (!params.person_id) params.person_id = undefined
  params.site_id = siteId
  maker_list(params)
    .then((res: any) => {
      console.log('影人列表: ', res)
      state.filmMakerList = res?.persons ?? []
      queryState.total = +res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.persons ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getFilmMakerList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
const deleteMaker = (item: MakerListData) => {
  console.log('item: ', item)
  deleteVisible.value = true
  deleteId.value = item.person_id
}
//编辑
const updateMaker = (item: MakerListData) => {
  console.log('item: ', item)
  router.push({ name: 'EditFilmMaker', query: { id: item.person_id } })
}
const editStatus = (checked: number, row: MakerListData) => {
  const data = {
    type: 9,
    status: checked,
    id: [row.person_id]
  }
  edit_status(data).then(() => {
    message.success(checked === 1 ? '启用成功' : '禁用成功')
    getFilmMakerList()
  })
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  maker_del({ person_id: [deleteId.value] }).then(() => {
    message.success('删除影人成功')
    deleteVisible.value = value
    getFilmMakerList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  导入影人库对话框事件
 */
const importConfirm = (value: any) => {
  console.log('value: ', value)
  importVisible.value = value
}
const importCancel = () => {
  importVisible.value = false
}
//根据类型获取图片
const getIcon = computed(() => (item: MakerListData) => {
  if (item.person_avatar_type === 1) return baseUrl.value + item.person_avatar
  return item.person_avatar
})
const getGender = computed(() => (item: any) => {
  if (item.person_gender === 1) return '男'
  if (item.person_gender === 2) return '女'
  return '-'
})
onMounted(() => {
  getFilmMakerList()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-classifyList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
